# Copyright (c) HySoP 2011-2024
#
# This file is part of HySoP software.
# See "https://particle_methods.gricad-pages.univ-grenoble-alpes.fr/hysop-doc/"
# for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
import numpy as np
from hysop.constants import Backend
from hysop.constants import HYSOP_REAL, HYSOP_INTEGER, HYSOP_BOOL
from hysop.tools.decorators import wraps
from hysop.tools.numerics import is_complex
from hysop.tools.htypes import check_instance, to_tuple, first_not_None
from hysop.tools.misc import get_default_args, args2kargs, kargs2args, get_argnames
from hysop.tools.hash import hash_id
from hysop.tools.warning import HysopWarning
from hysop.core.arrays import default_order, MemoryOrdering, MemoryType
from hysop.core.arrays.array_backend import ArrayBackend
from hysop.core.memory.allocator import AllocatorBase
from hysop.backend.host.host_buffer import HostBuffer
from hysop.testsenv import __HAS_OPENCL_BACKEND__
[docs]
def numpy_method(f):
@wraps(f)
def wrapper(*args, **kwargs):
from hysop.backend.host.host_array import HostArray
# build full args dictionnary
kargs = get_default_args(f)
kargs.update(kwargs)
kargs.update(args2kargs(f, args))
argnames, varargs = get_argnames(f)
has_args = ("args" in varargs) if varargs else False
has_kwargs = ("kwargs" in varargs) if varargs else False
if has_args or has_kwargs:
msg = "Wrapper does not support varargs and kwargs signatures for function {}:{}."
msg = msg.format(args[0].__name__, f.__name__)
raise RuntimeError(msg)
for k in kargs.keys():
if k not in argnames:
msg = "Unknown argument {} in function {}::{}(), possible ones are {}."
msg = msg.format(
k,
getattr(args[0], "__name__", type(args[0]).__name__),
f.__name__,
argnames,
)
raise ValueError(msg)
# format input arguments for numpy
backend = kargs.pop("self")
assert isinstance(backend, HostArrayBackend)
_, kargs = backend._prepare_args(**kargs)
backend._alloc_outputs(fname=f.__name__, kargs=kargs)
# numpy has some functions with badly documented and/or
# inacessible keywords so we go back to ordered args
args = kargs2args(f, kargs, remove=["self"])
if hasattr(np, f.__name__):
g = getattr(np, f.__name__)
if f.__name__ == "save":
ret = g(**kwargs)
else:
ret = g(*args)
else:
raise RuntimeError(f"numpy does not define function {f.__name__}.")
# wrap output
return backend._return(ret)
return wrapper
[docs]
class HostArrayBackend(ArrayBackend):
"""
Host array backend.
"""
__backends = {}
[docs]
@classmethod
def get_or_create(cls, allocator):
from hysop.backend.host.host_allocator import default_host_allocator
allocator = first_not_None(allocator, default_host_allocator)
key = (allocator,)
if key in cls.__backends:
return cls.__backends[key]
else:
obj = cls(allocator=allocator)
cls.__backends[key] = obj
return obj
def __init__(self, allocator, **kwds):
check_instance(allocator, AllocatorBase)
assert allocator.is_on_host(), "allocator does not allocate buffers on host."
super().__init__(allocator=allocator, **kwds)
def __str__(self):
return "host array backend"
[docs]
def get_kind(self):
return Backend.HOST
kind = property(get_kind)
[docs]
def get_host_array_backend(self):
return self
host_array_backend = property(get_host_array_backend)
[docs]
def short_description(self):
return ":HostBackend: tag={}, allocator={}".format(
self.tag, self.allocator.full_tag
)
############################
# BACKEND SPECIFIC METHODS #
[docs]
def can_wrap(self, handle):
"""
Should return True if handle is an Array or a array handle corresponding
this backend.
"""
from hysop.core.arrays.all import HostArray
return isinstance(handle, (HostArray, np.ndarray))
[docs]
def wrap(self, handle):
"""
Create a HostArray from an np.ndarray instance.
"""
from hysop.core.arrays.all import HostArray
if isinstance(handle, HostArray):
return handle
check_instance(handle, np.ndarray)
# if handle.dtype==np.bool:
# import warnings
# msg='HostArrayBackend: numpy np.bool array converted to HYSOP_BOOL={}.'
# msg=msg.format(HYSOP_BOOL.__name__)
# warnings.warn(msg, HysopWarning)
# return HostArray(backend=self, handle=handle.astype(HYSOP_BOOL))
# else:
# return HostArray(backend=self, handle=handle)
return HostArray(backend=self, handle=handle)
[docs]
def copyto(self, dst, src, reshape=False, queue=None, synchronize=True, **kwds):
"""
src is a HostArray
dst can be everything
"""
from hysop.core.arrays.all import HostArray
if __HAS_OPENCL_BACKEND__:
from hysop.core.arrays.all import OpenClArray
check_instance(src, HostArray)
src = src.reshape(dst.shape) if reshape else src
if dst.size != src.size:
raise ValueError("'dst' has non-matching size.")
if dst.dtype != src.dtype:
raise ValueError("'dst' has non-matching dtype.")
if dst.shape != src.shape:
raise ValueError("'dst' has non-matching shape.")
if dst.size == 0:
return
if isinstance(dst, HostArray):
dst.handle[...] = src
elif isinstance(dst, np.ndarray):
dst[...] = src
elif __HAS_OPENCL_BACKEND__ and isinstance(dst, OpenClArray):
queue = first_not_None(queue, dst.default_queue)
from hysop.backend.device.opencl.opencl_copy_kernel_launchers import (
OpenClCopyBufferRectLauncher,
)
kl = OpenClCopyBufferRectLauncher.from_slices("copyto", src=src, dst=dst)
evt = kl(queue=queue)
if synchronize:
evt.wait()
else:
return evt
else:
msg = "Unknown type to copy to ({}) for array of type {}."
msg = msg.format(dst.__class__, src.__class__)
raise TypeError(msg)
###########################
# ARRAY CREATION ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html
## ALLOCATED WITH BACKEND ALLOCATOR ##
[docs]
def array(
self,
shape,
dtype=HYSOP_REAL,
order=default_order,
min_alignment=None,
buf=None,
offset=0,
):
"""
Create a HostArray, see np.ndarray constructor.
If buf is None, a new one is allocated from backend allocator.
"""
order = self._arg(order)
shape = to_tuple(shape)
if dtype == np.bool_:
dtype = HYSOP_BOOL
import warnings
msg = f"HostArrayBackend: numpy bool array converted to hysop_bool={dtype}."
warnings.warn(msg, HysopWarning)
if buf is None:
assert offset == 0
allocator = self.allocator
dtype = np.dtype(dtype)
(size, nbytes, alignment) = self.get_alignment_and_size(
shape=shape, dtype=dtype, min_alignment=min_alignment
)
alloc = allocator.allocate_aligned(size, alignment=alignment)
handle = HostBuffer(
buffer=alloc,
shape=shape,
dtype=dtype,
order=order,
offset=0,
strides=None,
size=size,
)
array = self.wrap(handle=handle)
else:
handle = HostBuffer.frombuffer(buf, offset=offset, dtype=dtype)
handle = handle.reshape(shape=shape, order=order)
array = self.wrap(handle=handle)
return array
[docs]
def empty(self, shape, dtype=HYSOP_REAL, order=default_order, min_alignment=None):
"""
Return a new array of given shape and type, without initializing entries.
Data is allocated from backend allocator.
"""
a = self.array(
shape=shape, dtype=dtype, order=order, min_alignment=min_alignment
)
return a
[docs]
def full(
self,
shape,
fill_value,
dtype=HYSOP_REAL,
order=default_order,
min_alignment=None,
):
"""
Return a new array of given shape and type, filled with fill_value.
Data is allocated from backend allocator.
"""
a = self.empty(
shape=shape, dtype=dtype, order=order, min_alignment=min_alignment
)
self.fill(a=a, value=fill_value)
return a
[docs]
def zeros(self, shape, dtype=HYSOP_REAL, order=default_order, min_alignment=None):
"""
Return a new array of given shape and type, filled with zeros.
Data is allocated from backend allocator.
"""
return self.full(
shape=shape,
dtype=dtype,
order=order,
fill_value=0,
min_alignment=min_alignment,
)
[docs]
def ones(self, shape, dtype=HYSOP_REAL, order=default_order, min_alignment=None):
"""
Return a new array of given shape and type, filled with ones.
Data is allocated from backend allocator.
"""
return self.full(
shape=shape,
dtype=dtype,
order=order,
fill_value=1,
min_alignment=min_alignment,
)
[docs]
def empty_like(self, a, dtype=None, order=None, subok=True, shape=None):
"""
Return a new array with the same shape and type as a given array.
Data is allocated from backend allocator.
"""
self._unsupported_argument("empty_like", "subok", subok, True)
if (order is None) or (order == MemoryOrdering.SAME_ORDER):
try:
if a.flags.c_contiguous:
order = MemoryOrdering.C_CONTIGUOUS
elif a.flags.f_contiguous:
order = MemoryOrdering.F_CONTIGUOUS
else:
order = default_order
except AttributeError:
order = default_order
return self.empty(
shape=first_not_None(shape, a.shape),
dtype=first_not_None(dtype, a.dtype),
order=order,
)
[docs]
def full_like(self, a, fill_value, dtype=None, order=None, subok=True, shape=None):
"""
Return a new array with the same shape and type as a given array.
Data is allocated from backend allocator.
"""
a = self.empty_like(a=a, dtype=dtype, order=order, subok=subok, shape=shape)
self.fill(a, value=fill_value)
return a
[docs]
def zeros_like(self, a, dtype=None, order=None, subok=True, shape=None):
"""
Return an array of zeros with the same shape and type as a given array.
Data is allocated from backend allocator.
"""
return self.full_like(
a=a, fill_value=0, dtype=dtype, order=order, subok=subok, shape=shape
)
[docs]
def ones_like(self, a, dtype=None, order=None, subok=True, shape=None):
"""
Return an array of ones with the same shape and type as a given array.
Data is allocated from backend allocator.
"""
return self.full_like(
a=a, fill_value=1, dtype=dtype, order=order, subok=subok, shape=shape
)
# Filling facility
[docs]
def fill(self, a, value):
"""
Fill the array with given value.
"""
a.handle.fill(value)
#### ALLOCATED FROM WITHIN NUMPY ####
# Ones and zeros
[docs]
@numpy_method
def eye(self, N, M, k, dtype=None):
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def identity(self, n, dtype=None):
"""
Return the identity array.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
def copy(self, a, order=MemoryOrdering.SAME_ORDER):
"""
Return an array copy of the given object.
"""
b = self.empty_like(a, order=order)
b[...] = a[...]
return b
[docs]
@numpy_method
def asarray(self, a, dtype=None, order=default_order):
"""
Convert the input to an HostArray.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def asanyarray(self, a, dtype=None, order=default_order):
"""
Convert the input to an ndarray, but pass ndarray subclasses through.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def asmatrix(self, data, dtype=None):
"""
Interpret the input as a matrix.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def frombuffer(self, afer, dtype=HYSOP_REAL, count=-1, offset=0):
"""
Interpret a afer as a 1-dimensional array.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def fromfile(self, file, dtype=HYSOP_REAL, count=-1, sep=""):
"""
Construct an array from data in a text or binary file.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def fromfunction(self, function, shape, dtype=HYSOP_REAL):
"""
Construct an array by executing a function over each coordinate.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def fromiter(self, iterable, dtype=HYSOP_REAL, count=-1):
"""
Create a new 1-dimensional array from an iterable object.
Data is *not* allocated from backend allocator.
"""
pass
@numpy_method
def fromstring(self, string, dtype=HYSOP_REAL, count=-1, sep=""):
"""
A new 1-D array initialized from raw binary or text data in a string.
Data is *not* allocated from backend allocator.
"""
pass
@numpy_method
def loadtxt(
self,
fname,
dtype=HYSOP_REAL,
comments="#",
delimiter=None,
converters=None,
skiprows=0,
usecols=None,
unpack=False,
ndmin=0,
):
"""
Load data from a text file.
Data is *not* allocated from backend allocator.
"""
pass
# Numerical ranges
[docs]
def arange(self, *args, **kargs):
"""
Return evenly spaced values within a given interval.
Data is *not* allocated from backend allocator.
"""
if "dtype" not in kargs:
kargs["dtype"] = HYSOP_INTEGER
handle = np.arange(*args, **kargs)
return self.wrap(handle)
[docs]
@numpy_method
def linspace(
self, start, stop, num=50, endpoint=True, retstep=False, dtype=HYSOP_REAL
):
"""
Return evenly spaced numbers over a specified interval.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def logspace(self, start, stop, num=50, endpoint=True, base=10.0, dtype=HYSOP_REAL):
"""
Return numbers spaced evenly on a log scale.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def geomspace(self, start, stop, num=50, endpoint=True, dtype=HYSOP_REAL):
"""
Return numbers spaced evenly on a log scale (a geometric progression).
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def meshgrid(self, *xi, **kwargs):
"""
Return coordinate matrices from coordinate vectors.
Data is *not* allocated from backend allocator.
"""
pass
# Building matrices
[docs]
@numpy_method
def diag(self, v, k=0):
"""
Extract a diagonal or construct a diagonal array.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def diagflat(self, v, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def tri(self, N, M=None, k=0, dtype=HYSOP_REAL):
"""
An array with ones at and below the given diagonal and zeros elsewhere.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def tril(self, m, k):
"""
Lower triangle of an array.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def triu(self, m, k=0):
"""
Upper triangle of an array.
Data is *not* allocated from backend allocator.
"""
pass
[docs]
@numpy_method
def vander(self, x, N=None, increasing=False):
"""
Generate a Vandermonde matrix.
Data is *not* allocated from backend allocator.
"""
pass
###############################
# ARRAY MANIPULATION ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html
# Changing array shape
[docs]
@numpy_method
def reshape(self, a, newshape, order=default_order):
"""
Gives a new shape to an array without changing its data.
"""
pass
[docs]
@numpy_method
def ravel(self, a, order=MemoryOrdering.SAME_ORDER):
"""
Return a contiguous flattened array.
"""
pass
# Transpose-like operations
# /!\ those functions can alter the transposition state /!\
[docs]
@numpy_method
def moveaxis(self, a, source, destination):
"""
Move axes of an array to new positions.
"""
pass
[docs]
@numpy_method
def rollaxis(self, a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
"""
pass
[docs]
@numpy_method
def swapaxes(self, a, axis1, axis2):
"""
Interchange two axes of an array.
"""
pass
[docs]
@numpy_method
def transpose(self, a, axes=None):
"""
Permute the dimensions of an array.
"""
pass
# Changing number of dimensions
[docs]
@numpy_method
def atleast_1d(self, *arys):
"""
Convert inputs to arrays with at least one dimension.
"""
pass
[docs]
@numpy_method
def atleast_2d(self, *arys):
"""
View inputs as arrays with at least two dimensions.
"""
pass
[docs]
@numpy_method
def atleast_3d(self, *arys):
"""
View inputs as arrays with at least three dimensions.
"""
pass
[docs]
@numpy_method
def broadcast_to(self, array, shape, subok=False):
"""
Broadcast an array to a new shape.
"""
pass
[docs]
@numpy_method
def broadcast_arrays(self, *args, **kwargs):
"""
Broadcast any number of arrays against each other.
"""
pass
[docs]
@numpy_method
def expand_dims(self, a, axis):
"""
Expand the shape of an array.
"""
pass
[docs]
@numpy_method
def squeeze(self, a, axis=None):
"""
Remove single-dimensional entries from the shape of an array.
"""
pass
# Changing kind of array
[docs]
@numpy_method
def asfortranarray(self, a, dtype=None):
"""
Return an array laid out in Fortran order in memory.
"""
pass
[docs]
@numpy_method
def ascontiguousarray(self, a, dtype=None):
"""
Return a contiguous array in memory (C order).
"""
pass
[docs]
@numpy_method
def asarray_chkfinite(self, a, dtype=None, order=default_order):
"""
Convert the input to an array, checking for NaNs or Infs.
"""
pass
[docs]
@numpy_method
def asscalar(self, a):
"""
Convert an array of size 1 to its scalar equivalent.
"""
pass
[docs]
@numpy_method
def require(self, a, dtype=None, requirements=None):
"""
Return an ndarray of the provided type that satisfies requirements.
"""
pass
# Joining arrays
[docs]
@numpy_method
def concatenate(self, a, axis=0):
"""
Join a sequence of arrays along an existing axis.
"""
pass
[docs]
@numpy_method
def stack(self, arrays, axis=0):
"""
Join a sequence of arrays along a new axis.
"""
pass
[docs]
@numpy_method
def column_stack(self, tup):
"""
Stack 1-D arrays as columns into a 2-D array.
"""
pass
[docs]
@numpy_method
def dstack(self, tup):
"""
Stack arrays in sequence depth wise (along third axis).
"""
pass
[docs]
@numpy_method
def hstack(self, tup):
"""
Stack arrays in sequence horizontally (column wise).
"""
pass
[docs]
@numpy_method
def vstack(self, tup):
"""
Stack arrays in sequence vertically (row wise).
"""
pass
# Splitting arrays
[docs]
@numpy_method
def split(self, ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
"""
pass
[docs]
@numpy_method
def array_split(self, ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
"""
pass
[docs]
@numpy_method
def dsplit(self, ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
"""
pass
[docs]
@numpy_method
def hsplit(self, ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
"""
pass
[docs]
@numpy_method
def vsplit(self, ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
"""
pass
# Tiling arrays
[docs]
@numpy_method
def tile(self, A, reps):
"""
Construct an array by repeating A the number of times given by reps.
"""
pass
[docs]
@numpy_method
def repeat(self, a, repeats, axis=None):
"""
Repeat elements of an array.
"""
pass
# Adding and removing elements
[docs]
@numpy_method
def delete(self, arr, obj, axis=None):
"""
Return a new array with sub-arrays along an axis deleted.
"""
pass
[docs]
@numpy_method
def insert(self, arr, obj, values, axis=None):
"""
Insert values along the given axis before the given indices.
"""
pass
[docs]
@numpy_method
def append(self, arr, values, axis=None):
"""
Append values to the end of an array.
"""
pass
[docs]
@numpy_method
def resize(self, a, new_shape):
"""
Return a new array with the specified shape.
"""
pass
[docs]
@numpy_method
def trim_zeros(self, filt, trim="fb"):
"""
Trim the leading and/or trailing zeros from a 1-D array or sequence.
"""
pass
@numpy_method
def unique(self, ar, return_index=False, return_inverse=False, return_counts=False):
"""
Find the unique elements of an array.
"""
pass
# Rearranging elements
[docs]
@numpy_method
def flip(self, m, axis):
"""
Reverse the order of elements in an array along the given axis.
"""
pass
[docs]
@numpy_method
def fliplr(self, m):
"""
Flip array in the left/right direction.
"""
pass
[docs]
@numpy_method
def flipud(self, m):
"""
Flip array in the up/down direction.
"""
pass
[docs]
@numpy_method
def roll(self, a, shift, axis=None):
"""
Roll array elements along a given axis.
"""
pass
[docs]
@numpy_method
def rot90(self, m, k=1, axes=(0, 1)):
"""
Rotate an array by 90 degrees in the plane specified by axes.
"""
pass
#####################
# BINARY OPERATIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.bitwise.html
# Elementwise bit operations
[docs]
@numpy_method
def bitwise_and(self, x1, x2, out=None):
"""
Compute the bit-wise AND of two arrays element-wise.
"""
pass
[docs]
@numpy_method
def bitwise_or(self, x1, x2, out=None):
"""
Compute the bit-wise OR of two arrays element-wise.
"""
pass
[docs]
@numpy_method
def bitwise_xor(self, x1, x2, out=None):
"""
Compute the bit-wise XOR of two arrays element-wise.
"""
pass
[docs]
@numpy_method
def invert(self, x, out=None):
"""
Compute bit-wise inversion, or bit-wise NOT, element-wise.
"""
pass
[docs]
@numpy_method
def left_shift(self, x1, x2, out=None):
"""
Shift the bits of an integer to the left.
"""
pass
[docs]
@numpy_method
def right_shift(self, x1, x2, out=None):
"""
Shift the bits of an integer to the right.
"""
pass
# Bit packing
[docs]
@numpy_method
def packbits(self, myarray, axis=None):
"""
Packs the elements of a binary-valued array into bits in a uint8 array.
"""
pass
[docs]
@numpy_method
def unpackbits(self, myarray, axis=None):
"""
Unpacks elements of a uint8 array into a binary-valued output array.
"""
pass
# Output formatting
@numpy_method
def binary_repr(self, num, width=None):
"""
Return the binary representation of the input number as a string.
"""
pass
##############################
# DISCRETE FOURIER TRANSFORM #
# See https://docs.scipy.org/doc/numpy/reference/routines.fft.html
# Standard FFTs
[docs]
@numpy_method
def fft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform.
"""
pass
[docs]
@numpy_method
def ifft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional inverse discrete Fourier Transform.
"""
pass
[docs]
@numpy_method
def fft2(self, a, s=None, axes=None, norm=None):
"""
Compute the 2-dimensional discrete Fourier Transform
"""
pass
[docs]
@numpy_method
def ifft2(self, a, s=None, axes=None, norm=None):
"""
Compute the 2-dimensional inverse discrete Fourier Transform.
"""
pass
[docs]
@numpy_method
def fftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional discrete Fourier Transform.
"""
pass
[docs]
@numpy_method
def ifftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
"""
pass
# Real FFTs
[docs]
@numpy_method
def rfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform for real input.
"""
pass
[docs]
@numpy_method
def irfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the inverse of the n-point DFT for real input.
"""
pass
[docs]
@numpy_method
def rfft2(self, a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional FFT of a real array.
"""
pass
[docs]
@numpy_method
def irfft2(self, a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional inverse FFT of a real array.
"""
pass
[docs]
@numpy_method
def rfftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional discrete Fourier Transform for real input.
"""
pass
[docs]
@numpy_method
def irfftn(self, a, s=None, axes=None, norm=None):
"""
Compute the inverse of the N-dimensional FFT of real input.
"""
pass
# Hermitian FFTs
[docs]
@numpy_method
def hfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real spectrum.
"""
pass
[docs]
@numpy_method
def ihfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the inverse FFT of a signal that has Hermitian symmetry.
"""
pass
# Helper routines
[docs]
@numpy_method
def fftfreq(self, n=None, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies.
"""
pass
[docs]
@numpy_method
def rfftfreq(self, n=None, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft).
"""
pass
[docs]
@numpy_method
def fftshift(self, x, axes=None):
"""
Shift the zero-frequency component to the center of the spectrum.
"""
pass
[docs]
@numpy_method
def ifftshift(self, x, axes=None):
"""
The inverse of fftshift.
"""
pass
##########################
# FUNCTIONAL PROGRAMMING #
# See https://docs.scipy.org/doc/numpy/reference/routines.functional.html
[docs]
@numpy_method
def vectorize(
self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None
):
"""
Generalized function class.
"""
pass
[docs]
@numpy_method
def frompyfunc(self, func, nin, nout):
"""
Takes an arbitrary Python function and returns a NumPy ufunc.
"""
pass
[docs]
@numpy_method
def piecewise(self, x, condlist, funclist, *args, **kw):
"""
Evaluate a piecewise-defined function.
"""
pass
####################
# INPUT AND OUTPUT #
# See https://docs.scipy.org/doc/numpy/reference/routines.io.html
# NumPy binary files (NPY, NPZ)
[docs]
@numpy_method
def load(
self, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding="ASCII"
):
"""
Load arrays or pickled objects from .npy, .npz or pickled files.
"""
pass
[docs]
@numpy_method
def save(self, arr, file, allow_pickle=True, fix_imports=True):
"""
Save an array to a binary file in NumPy .npy format.
"""
pass
[docs]
@numpy_method
def savez(self, file, *args, **kwds):
"""
Save several arrays into a single file in uncompressed .npz format.
"""
pass
[docs]
@numpy_method
def savez_compressed(self, file, *args, **kwds):
"""
Save several arrays into a single file in compressed .npz format.
"""
pass
# Text files
[docs]
@numpy_method
def loadtxt(
self,
dtype=HYSOP_REAL,
comments="#",
delimiter=None,
converters=None,
skiprows=0,
usecols=None,
unpack=False,
ndmin=0,
):
"""
Load data from a text file.
"""
pass
[docs]
@numpy_method
def savetxt(
self,
fname,
X,
fmt="%.18e",
delimiter=" ",
newline="\n",
header="",
footer="",
comments="# ",
):
"""
Save an array to a text file.
"""
pass
[docs]
@numpy_method
def genfromtxt(
self,
fname,
dtype=HYSOP_REAL,
comments="#",
delimiter=None,
skip_header=0,
skip_footer=0,
converters=None,
missing_values=None,
filling_values=None,
usecols=None,
names=None,
excludelist=None,
deletechars=None,
replace_space="_",
autostrip=False,
case_sensitive=True,
defaultfmt="f%i",
unpack=None,
usemask=False,
loose=True,
invalid_raise=True,
max_rows=None,
):
"""
Load data from a text file, with missing values handled as specified.
"""
pass
[docs]
@numpy_method
def fromregex(self, file, regexp, dtype):
"""
Construct an array from a text file, using regular expression parsing.
"""
pass
[docs]
@numpy_method
def fromstring(self, string, dtype=HYSOP_REAL, count=-1, sep=""):
"""
A new 1-D array initialized from raw binary or text data in a string.
"""
pass
# String formatting
[docs]
@numpy_method
def array2string(
self,
a,
max_line_width=None,
precision=None,
suppress_small=None,
separator=" ",
prefix="",
style=repr,
formatter=None,
):
"""
Return a string representation of an array.
"""
pass
[docs]
@numpy_method
def array_repr(self, arr, max_line_width=None, precision=None, supress_small=None):
"""
Return the string representation of an array.
"""
pass
[docs]
@numpy_method
def array_str(self, a, max_line_width=None, precision=None, suppress_small=None):
"""
Return a string representation of the data in an array.
"""
pass
# Text formatting options
[docs]
@numpy_method
def set_printoptions(
self,
precision=None,
threshold=None,
edgeitems=None,
linewidth=None,
suppress=None,
nanstr=None,
infstr=None,
formatter=None,
):
"""
Set printing options.
"""
pass
[docs]
@numpy_method
def get_printoptions(self):
"""
Return the current print options.
"""
pass
[docs]
@numpy_method
def set_string_function(self, f, repr=True):
"""
Set a Python function to be used when pretty printing arrays.
"""
pass
# Base-n representations
[docs]
@numpy_method
def binary_repr(self, num, width=None):
"""
Return the binary representation of the input number as a string.
"""
pass
[docs]
@numpy_method
def base_repr(self, number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
"""
pass
######################
### LINEAR ALGEBRA ###
# See https://docs.scipy.org/doc/numpy/reference/routines.linalg.html
# Matrix and vector products
[docs]
@numpy_method
def dot(self, a, b, out=None):
"""
Dot product of two arrays.
"""
pass
[docs]
@numpy_method
def vdot(self, a, b):
"""
Return the dot product of two vectors.
"""
pass
[docs]
@numpy_method
def inner(self, a, b):
"""
Inner product of two arrays.
"""
pass
[docs]
@numpy_method
def outer(self, a, b, out=None):
"""
Compute the outer product of two vectors.
"""
pass
[docs]
@numpy_method
def matmul(self, a, b, out=None):
"""
Matrix product of two arrays.
"""
pass
[docs]
@numpy_method
def tensordot(self, a, b, axes=2):
"""
Compute tensor dot product along specified axes for arrays >= 1-D.
"""
pass
[docs]
@numpy_method
def einsum(
self,
subscripts,
out=None,
dtype=None,
order=MemoryOrdering.SAME_ORDER,
casting="safe",
optimize=False,
*operands,
):
"""
Evaluates the Einstein summation convention on the operands.
"""
pass
[docs]
@numpy_method
def matrix_power(self, M, n):
"""
Raise a square matrix to the integer power n.
"""
pass
[docs]
@numpy_method
def kron(self, a, b):
"""
Kronecker product of two arrays.
"""
pass
# Decompositions
[docs]
@numpy_method
def cholesky(self, a):
"""
Cholesky decomposition.
"""
pass
[docs]
@numpy_method
def qr(self, a, mode="reduced"):
"""
Compute the qr factorization of a matrix.
"""
pass
[docs]
@numpy_method
def svd(self, a, full_matrices=True, compute_uv=True):
"""
Singular Value Decomposition.
"""
pass
# Matrix eigenvalues
[docs]
@numpy_method
def eig(self, a):
"""
Compute the eigenvalues and right eigenvectors of a square array.
"""
pass
[docs]
@numpy_method
def eigh(self, a, UPLO="L"):
"""
Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix.
"""
pass
[docs]
@numpy_method
def eigvals(self, a):
"""
Compute the eigenvalues of a general matrix.
"""
pass
[docs]
@numpy_method
def eigvalsh(self, a, UPLO="L"):
"""
Compute the eigenvalues of a Hermitian or real symmetric matrix.
"""
pass
# Norms and other numbers
[docs]
@numpy_method
def norm(self, x, ord=None, axis=None, keepdims=False):
"""
Matrix or vector norm.
"""
pass
[docs]
@numpy_method
def cond(self, x, p=None):
"""
Compute the condition number of a matrix.
"""
pass
[docs]
@numpy_method
def det(self, a):
"""
Compute the determinant of an array.
"""
pass
[docs]
@numpy_method
def matrix_rank(self, M, tol=None):
"""
Return matrix rank of array using SVD method
"""
pass
[docs]
@numpy_method
def slogdet(self, a):
"""
Compute the sign and natural logarithm of the determinant of an array.
"""
pass
[docs]
@numpy_method
def trace(self, a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""
Return the sum along diagonals of the array.
"""
pass
# Solving equations and inverting matrices
[docs]
@numpy_method
def solve(self, a, b):
"""
Solve a linear matrix equation, or system of linear scalar equations.
"""
pass
[docs]
@numpy_method
def tensorsolve(self, a, b, axes=None):
"""
Solve the tensor equation a x = b for x.
"""
pass
[docs]
@numpy_method
def lstsq(self, a, b, rcond=-1):
"""
Return the least-squares solution to a linear matrix equation.
"""
pass
[docs]
@numpy_method
def inv(self, a):
"""
Compute the (multiplicative) inverse of a matrix.
"""
pass
[docs]
@numpy_method
def pinv(self, a, rcond=1e-15):
"""
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
"""
pass
[docs]
@numpy_method
def tensorinv(self, a, ind=2):
"""
Compute the 'inverse' of an N-dimensional array.
"""
pass
###################
# LOGIC FUNCTIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.logic.html
# Truth value testing
[docs]
@numpy_method
def any(self, a, axis=None, out=None):
"""
Test whether any array elements along a given axis evaluate to True.
"""
pass
[docs]
@numpy_method
def all(self, a, axis=None, out=None):
"""
Test whether all array elements along a given axis evaluate to True.
"""
pass
# Array contents
[docs]
@numpy_method
def isfinite(self, x, out=None):
"""
Test element-wise for finiteness (not infinity or not Not a Number).
"""
pass
[docs]
@numpy_method
def isinf(self, x, out=None):
"""
Test element-wise for positive or negative infinity.
"""
pass
[docs]
@numpy_method
def isnan(self, x, out=None):
"""
Test element-wise for NaN and return result as a boolean array.
"""
pass
[docs]
@numpy_method
def isneginf(self, x, out=None):
"""
Test element-wise for negative infinity, return result as bool array.
"""
pass
[docs]
@numpy_method
def isposinf(self, x, out=None):
"""
Test element-wise for positive infinity, return result as bool array.
"""
pass
# Logical operations
[docs]
@numpy_method
def logical_and(self, x1, x2, out=None):
"""
Compute the truth value of x1 AND x2 element-wise.
"""
pass
[docs]
@numpy_method
def logical_or(self, x1, x2, out=None):
"""
Compute the truth value of x1 OR x2 element-wise.
"""
pass
[docs]
@numpy_method
def logical_not(self, x, out=None):
"""
Compute the truth value of NOT x element-wise.
"""
pass
[docs]
@numpy_method
def logical_xor(self, x1, x2, out=None):
"""
Compute the truth value of x1 XOR x2, element-wise.
"""
pass
# Comparisson
[docs]
@numpy_method
def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
"""
Returns True if two arrays are element-wise equal within a tolerance.
"""
pass
[docs]
@numpy_method
def isclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
"""
Returns a boolean array where two arrays are element-wise equal within a tolerance.
"""
pass
[docs]
@numpy_method
def array_equal(self, a1, a2):
"""
True if two arrays have the same shape and elements, False otherwise.
"""
pass
[docs]
@numpy_method
def array_equiv(self, a1, a2):
"""
returns True if input arrays are shape consistent and all elements equal.
"""
pass
[docs]
@numpy_method
def greater(self, x1, x2, out=None):
"""
Return the truth value of (x1 > x2) element-wise.
"""
pass
[docs]
@numpy_method
def greater_equal(self, x1, x2, out=None):
"""
Return the truth value of (x1 >= x2) element-wise.
"""
pass
[docs]
@numpy_method
def less(self, x1, x2, out=None):
"""
Return the truth value of (x1 < x2) element-wise.
"""
pass
[docs]
@numpy_method
def less_equal(self, x1, x2, out=None):
"""
Return the truth value of (x1 =< x2) element-wise.
"""
pass
[docs]
@numpy_method
def equal(self, x1, x2, out=None):
"""
Return (x1 == x2) element-wise.
"""
pass
[docs]
@numpy_method
def not_equal(self, x1, x2, out=None):
"""
Return (x1 != x2) element-wise.
"""
pass
##########################
# MATHEMATICAL FUNCTIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.math.html
# Trigonometric functions
[docs]
@numpy_method
def sin(self, x, out=None):
"""
Trigonometric sine, element-wise.
"""
pass
[docs]
@numpy_method
def cos(self, x, out=None):
"""
Cosine element-wise.
"""
pass
[docs]
@numpy_method
def tan(self, x, out=None):
"""
Compute tangent element-wise.
"""
pass
[docs]
@numpy_method
def arcsin(self, x, out=None):
"""
Inverse sine, element-wise.
"""
pass
[docs]
@numpy_method
def arccos(self, x, out=None):
"""
Trigonometric inverse cosine, element-wise.
"""
pass
[docs]
@numpy_method
def arctan(self, x, out=None):
"""
Trigonometric inverse tangent, element-wise.
"""
pass
[docs]
@numpy_method
def arctan2(self, x1, x2, out=None):
"""
Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
"""
pass
[docs]
@numpy_method
def hypot(self, x1, x2, out=None):
"""
Given the legs of a right triangle, return its hypotenuse.
"""
pass
[docs]
@numpy_method
def unwrap(self, p, discont=3.141592653589793, axis=-1):
"""
Unwrap by changing deltas between values to 2*pi complement.
"""
pass
[docs]
@numpy_method
def deg2rad(self, x, out=None):
"""
Convert angles from degrees to radians.
"""
pass
[docs]
@numpy_method
def rad2deg(self, x, out=None):
"""
Convert angles from radians to degrees.
"""
pass
# Hyperbolic functions
[docs]
@numpy_method
def sinh(self, x, out=None):
"""
Hyperbolic sine, element-wise.
"""
pass
[docs]
@numpy_method
def cosh(self, x, out=None):
"""
Hyperbolic cosine, element-wise.
"""
pass
[docs]
@numpy_method
def tanh(self, x, out=None):
"""
Compute hyperbolic tangent element-wise.
"""
pass
[docs]
@numpy_method
def arcsinh(self, x, out=None):
"""
Inverse hyperbolic sine element-wise.
"""
pass
[docs]
@numpy_method
def arccosh(self, x, out=None):
"""
Inverse hyperbolic cosine, element-wise.
"""
pass
[docs]
@numpy_method
def arctanh(self, x, out=None):
"""
Inverse hyperbolic tangent element-wise.
"""
pass
# Rounding
[docs]
@numpy_method
def around(self, a, decimals=0, out=None):
"""
Evenly round to the given number of decimals.
"""
pass
[docs]
@numpy_method
def fix(self, x, y=None):
"""
Round to nearest integer towards zero.
"""
pass
[docs]
@numpy_method
def rint(self, x, out=None):
"""
Round elements of the array to the nearest integer.
"""
pass
[docs]
@numpy_method
def floor(self, x, out=None):
"""
Return the floor of the input, element-wise.
"""
pass
[docs]
@numpy_method
def ceil(self, x, out=None):
"""
Return the ceiling of the input, element-wise.
"""
pass
[docs]
@numpy_method
def trunc(self, x, out=None):
"""
Return the truncated value of the input, element-wise.
"""
pass
# Sums, product, differences
[docs]
@numpy_method
def prod(self, a, axis=None, dtype=None, out=None):
"""
Return the product of array elements over a given axis.
"""
pass
[docs]
@numpy_method
def sum(self, a, axis=None, dtype=None, out=None):
"""
Sum of array elements over a given axis.
"""
pass
[docs]
@numpy_method
def nanprod(self, a, axis=None, dtype=None, out=None):
"""
Return the product of array elements over a given axis treating
Not a Numbers (NaNs) as ones.
"""
pass
[docs]
@numpy_method
def nansum(self, a, axis=None, dtype=None, out=None):
"""
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
"""
pass
[docs]
@numpy_method
def cumprod(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of elements along a given axis.
"""
pass
[docs]
@numpy_method
def cumsum(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative sum of the elements along a given axis.
"""
pass
[docs]
@numpy_method
def nancumprod(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of array elements over a given axis treating
Not a Numbers (NaNs) as one.
"""
pass
[docs]
@numpy_method
def nancumsum(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative sum of array elements over a given axis treating
Not a Numbers (NaNs) as zero.
"""
pass
[docs]
@numpy_method
def diff(self, a, n=1, axis=-1):
"""
Calculate the n-th discrete difference along given axis.
"""
pass
[docs]
@numpy_method
def ediff1d(self, ary, to_end=None, to_begin=None):
"""
The differences between consecutive elements of an array.
"""
pass
[docs]
@numpy_method
def gradient(self, f, *varargs, **kwargs):
"""
Return the gradient of an N-dimensional array.
"""
pass
[docs]
@numpy_method
def cross(self, a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
"""
Return the cross product of two (arrays of) vectors.
"""
pass
[docs]
@numpy_method
def trapz(self, y, x=None, dx=1.0, axis=-1):
"""
Integrate along the given axis using the composite trapezoidal rule.
"""
pass
# Exponents and logarithms
[docs]
@numpy_method
def exp(self, x, out=None):
"""
Calculate the exponential of all elements in the input array.
"""
pass
[docs]
@numpy_method
def exp2(self, x, out=None):
"""
Calculate 2**p for all p in the input array.
"""
pass
[docs]
@numpy_method
def expm1(self, x, out=None):
"""
Calculate exp(x) - 1 for all elements in the array.
"""
pass
[docs]
@numpy_method
def log(self, x, out=None):
"""
Natural logarithm, element-wise.
"""
pass
[docs]
@numpy_method
def log2(self, x, out=None):
"""
Base-2 logarithm of x.
"""
pass
[docs]
@numpy_method
def log10(self, x, out=None):
"""
Return the base 10 logarithm of the input array, element-wise.
"""
pass
[docs]
@numpy_method
def log1p(self, x, out=None):
"""
Return the natural logarithm of one plus the input array, element-wise.
"""
pass
[docs]
@numpy_method
def logaddexp(self, x1, x2, out=None):
"""
Logarithm of the sum of exponentiations of the inputs.
"""
pass
[docs]
@numpy_method
def logaddexp2(self, x1, x2, out=None):
"""
Logarithm of the sum of exponentiations of the inputs in base-2.
"""
pass
# Other special functions
[docs]
@numpy_method
def i0(self, x):
"""
Modified Bessel function of the first kind, order 0.
"""
pass
[docs]
@numpy_method
def sinc(self, x):
"""
Return the sinc function.
"""
pass
# Floating point routines
[docs]
@numpy_method
def signbit(self, x, out=None):
"""
Returns element-wise True where signbit is set (less than zero).
"""
pass
[docs]
@numpy_method
def copysign(self, x1, x2, out=None):
"""
Change the sign of x1 to that of x2, element-wise.
"""
pass
[docs]
@numpy_method
def frexp(self, x, out1=None, out2=None):
"""
Decompose the elements of x into mantissa and twos exponent.
"""
pass
[docs]
@numpy_method
def ldexp(self, x1, x2, out=None):
"""
Returns x1 * 2**x2, element-wise.
"""
pass
# Arithmetic operations
[docs]
@numpy_method
def add(self, x1, x2, out=None):
"""
Add arguments element-wise.
"""
pass
[docs]
@numpy_method
def reciprocal(self, x, out=None):
"""
Return the reciprocal of the argument, element-wise.
"""
pass
[docs]
@numpy_method
def negative(self, x, out=None):
"""
Numerical negative, element-wise.
"""
pass
[docs]
@numpy_method
def multiply(self, x1, x2, out=None):
"""
Multiply arguments element-wise.
"""
pass
[docs]
@numpy_method
def divide(self, x1, x2, out=None):
"""
Divide arguments element-wise.
"""
pass
@numpy_method
def power(self, x1, x2, out=None):
"""
First array elements raised to powers from second array, element-wise.
"""
pass
[docs]
@numpy_method
def subtract(self, x1, x2, out=None):
"""
Subtract arguments, element-wise.
"""
pass
[docs]
@numpy_method
def true_divide(self, x1, x2, out=None):
"""
Returns a true division of the inputs, element-wise.
"""
pass
[docs]
@numpy_method
def floor_divide(self, x1, x2, out=None):
"""
Return the largest integer smaller or equal to the division of the inputs.
"""
pass
[docs]
@numpy_method
def fmod(self, x1, x2, out=None):
"""
Return the element-wise remainder of division.
"""
pass
[docs]
@numpy_method
def mod(self, x1, x2, out=None):
"""
Return element-wise remainder of division.
"""
pass
[docs]
@numpy_method
def modf(self, x, out1=None, out2=None):
"""
Return the fractional and integral parts of an array, element-wise.
"""
pass
# Handling complex numbers
[docs]
@numpy_method
def angle(self, z, deg=False):
"""
Return the angle of the complex argument.
"""
pass
[docs]
@numpy_method
def real(self, val):
"""
Return the real part of the elements of the array.
"""
pass
[docs]
@numpy_method
def imag(self, val):
"""
Return the imaginary part of the elements of the array.
"""
pass
[docs]
@numpy_method
def conj(self, x, out=None):
"""
Return the complex conjugate, element-wise.
"""
pass
# Miscellanous
[docs]
@numpy_method
def convolve(self, a, v, mode="full"):
"""
Returns the discrete, linear convolution of two one-dimensional sequences.
"""
pass
[docs]
@numpy_method
def clip(self, a, a_min, a_max, out=None):
"""
Clip (limit) the values in an array.
"""
pass
[docs]
def clip_components(self, a, a_min, a_max, out=None):
"""
Clip (limit) the values in an array.
"""
assert is_complex(a)
if out is None:
out = np.empty_like(a)
##NG 26 sep 2023: add .real after a_min and a_max
np.clip(a.real, a_min.real, a_max.real, out.real)
np.clip(a.imag, a_min.real, a_max.real, out.imag)
return out
[docs]
@numpy_method
def sqrt(self, x, out=None):
"""
Return the positive square-root of an array, element-wise.
"""
pass
[docs]
@numpy_method
def cbrt(self, x, out=None):
"""
Return the cube-root of an array, element-wise.
"""
pass
[docs]
@numpy_method
def square(self, x, out=None):
"""
Return the element-wise square of the input.
"""
pass
[docs]
@numpy_method
def nan_to_num(self, x):
"""
Replace nan with zero and inf with finite numbers.
"""
pass
[docs]
@numpy_method
def real_if_close(self, a, tol=100):
"""
If complex input returns a real array if complex parts are close to zero.
"""
pass
[docs]
@numpy_method
def interp(self, x, xp, fp, left=None, right=None, period=None):
"""
One-dimensional linear interpolation.
"""
pass
[docs]
@numpy_method
def maximum(self, x1, x2, out=None):
"""
Element-wise maximum of array elements.
"""
pass
[docs]
@numpy_method
def minimum(self, x1, x2, out=None):
"""
Element-wise minimum of array elements.
"""
pass
[docs]
@numpy_method
def fmin(self, x1, x2, out=None):
"""
Element-wise maximum of array elements, ignore NaNs.
"""
pass
[docs]
@numpy_method
def fmax(self, x1, x2, out=None):
"""
Element-wise minimum of array elements, ignore NaNs.
"""
pass
[docs]
@numpy_method
def fabs(self, x, out=None):
"""
Calculate the absolute value element-wise, outputs HYSOP_REAL unless out is set.
"""
pass
[docs]
@numpy_method
def absolute(self, x, out=None):
"""
Calculate the absolute value element-wise.
"""
pass
[docs]
@numpy_method
def sign(self, x, out=None):
"""
Returns an element-wise indication of the sign of a number.
"""
pass
###################
# RANDOM SAMPLING #
# See https://docs.scipy.org/doc/numpy/reference/routines.random.html
# Simple random data
[docs]
def rand(self, shape=None, out=None):
"""
Random values in a given shape.
"""
if out is not None:
shape = out.shape
else:
shape = tuple(shape)
handle = np.random.rand(*shape)
if out is not None:
out[...] = handle
return out
else:
return self.wrap(handle)
[docs]
def randn(self, *args):
"""
Return a sample (or samples) from the 'standard normal' distribution.
"""
from hysop.backend.host.host_array import HostArray
handle = np.random.randn(*args)
return self.wrap(handle)
[docs]
@numpy_method
def randint(self, low, high=None, size=None, dtype=HYSOP_INTEGER):
"""
Return random integers from low (inclusive) to high (exclusive).
"""
pass
[docs]
@numpy_method
def random_integers(self, low, high=None, size=None):
"""
Random integers of type np.int between low and high, inclusive.
"""
pass
[docs]
@numpy_method
def random_sample(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
pass
[docs]
@numpy_method
def random(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
pass
[docs]
@numpy_method
def ranf(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
pass
[docs]
@numpy_method
def sample(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
pass
[docs]
@numpy_method
def choice(self, a, size=None, replace=True, p=None):
"""
Generates a random sample from a given 1-D array
"""
pass
[docs]
@numpy_method
def bytes(self, length):
"""
Return random bytes.
"""
pass
# Permutations
[docs]
@numpy_method
def shuffle(self, x):
"""
Modify a sequence in-place by shuffling its contents.
"""
pass
[docs]
@numpy_method
def permutation(self, x):
"""
Randomly permute a sequence, or return a permuted range.
"""
pass
# Distributions
[docs]
@numpy_method
def beta(self, a, b, size=None):
"""
Draw samples from a Beta distribution.
"""
pass
[docs]
@numpy_method
def binomial(self, n, p, size=None):
"""
Draw samples from a binomial distribution.
"""
pass
[docs]
@numpy_method
def chisquare(self, df, size=None):
"""
Draw samples from a chi-square distribution.
"""
pass
[docs]
@numpy_method
def dirichlet(self, alpha, size=None):
"""
Draw samples from the Dirichlet distribution.
"""
pass
[docs]
@numpy_method
def exponential(self, scale=1.0, size=None):
"""
Draw samples from an exponential distribution.
"""
pass
[docs]
@numpy_method
def f(self, dfnum, dfden, size=None):
"""
Draw samples from an F distribution.
"""
pass
[docs]
@numpy_method
def gamma(self, shape, scale=1.0, size=None):
"""
Draw samples from a Gamma distribution.
"""
pass
[docs]
@numpy_method
def geometric(self, p, size=None):
"""
Draw samples from the geometric distribution.
"""
pass
[docs]
@numpy_method
def gumbel(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from a Gumbel distribution.
"""
pass
[docs]
@numpy_method
def hypergeometric(self, ngood, nbad, nsample, size=None):
"""
Draw samples from a Hypergeometric distribution.
"""
pass
[docs]
@numpy_method
def laplace(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from the Laplace or double exponential distribution with specified location (or mean=0.0) and scale (decay).
"""
pass
[docs]
@numpy_method
def logistic(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from a logistic distribution.
"""
pass
[docs]
@numpy_method
def lognormal(self, mean=0.0, sigma=1.0, size=None):
"""
Draw samples from a log-normal distribution.
"""
pass
[docs]
@numpy_method
def logseries(self, p, size=None):
"""
Draw samples from a logarithmic series distribution.
"""
pass
[docs]
@numpy_method
def multinomial(self, n, pvals, size=None):
"""
Draw samples from a multinomial distribution.
"""
pass
[docs]
@numpy_method
def multivariate_normal(self, mean, cov, size=None):
"""
Draw random samples from a multivariate normal distribution.
"""
pass
[docs]
@numpy_method
def negative_binomial(self, n, p, size=None):
"""
Draw samples from a negative binomial distribution.
"""
pass
[docs]
@numpy_method
def noncentral_chisquare(self, df, nonc, size=None):
"""
Draw samples from a noncentral chi-square distribution.
"""
pass
[docs]
@numpy_method
def noncentral_f(self, dfnum, dfden, nonc, size=None):
"""
Draw samples from the noncentral F distribution.
"""
pass
[docs]
@numpy_method
def normal(self, loc=0.0, scale=1.0, size=None):
"""
Draw random samples from a normal (Gaussian) distribution.
"""
pass
[docs]
@numpy_method
def pareto(self, a, size=None):
"""
Draw samples from a Pareto II or Lomax distribution with specified shape.
"""
pass
[docs]
@numpy_method
def poisson(self, lam, size=None):
"""
Draw samples from a Poisson distribution.
"""
pass
[docs]
@numpy_method
def power(self, a, size=None):
"""
Draws samples in 0, 1 from a power distribution with positive exponent a - 1.
"""
pass
[docs]
@numpy_method
def rayleigh(self, scale=1.0, size=None):
"""
Draw samples from a Rayleigh distribution.
"""
pass
[docs]
@numpy_method
def standard_cauchy(self, size=None):
"""
Draw samples from a standard Cauchy distribution with mode = 0.
"""
pass
[docs]
@numpy_method
def standard_exponential(self, size=None):
"""
Draw samples from the standard exponential distribution.
"""
pass
[docs]
@numpy_method
def standard_gamma(self, shape, size=None):
"""
Draw samples from a standard Gamma distribution.
"""
pass
[docs]
@numpy_method
def standard_normal(self, size=None):
"""
Draw samples from a standard Normal distribution (mean=0.0, stdev=1).
"""
pass
[docs]
@numpy_method
def standard_t(self, df, size=None):
"""
Draw samples from a standard Student's t distribution with df degrees of freedom.
"""
pass
[docs]
@numpy_method
def triangular(self, left, mode, right, size=None):
"""
Draw samples from the triangular distribution over the interval left, right.
"""
pass
[docs]
@numpy_method
def vonmises(self, mu, kappa, size=None):
"""
Draw samples from a von Mises distribution.
"""
pass
[docs]
@numpy_method
def wald(self, mean=0.0, scale=1.0, size=None):
"""
Draw samples from a Wald, or inverse Gaussian, distribution.
"""
pass
[docs]
@numpy_method
def weibull(self, a, size=None):
"""
Draw samples from a Weibull distribution.
"""
pass
[docs]
@numpy_method
def zipf(self, a, size=None):
"""
Draw samples from a Zipf distribution.
"""
pass
# Random generator
[docs]
@numpy_method
def seed(self, seed=None):
"""
Seed the generator.
"""
pass
[docs]
@numpy_method
def get_state(self):
"""
Return a tuple representing the internal state of the generator.
"""
pass
[docs]
@numpy_method
def set_state(self, state):
"""
Set the internal state of the generator from a tuple.
"""
pass
################
# SET ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.set.html
# Making proper sets
[docs]
@numpy_method
def unique(self, ar, return_index=False, return_inverse=False, return_counts=False):
"""
Find the unique elements of an array.
"""
pass
# Boolean operations
[docs]
@numpy_method
def in1d(self, ar1, ar2, assume_unique=False, invert=False):
"""
Test whether each element of a 1-D array is also present in a second array.
"""
pass
[docs]
@numpy_method
def intersect1d(self, ar1, ar2, assume_unique=False):
"""
Find the intersection of two arrays.
"""
pass
[docs]
@numpy_method
def setdiff1d(self, ar1, ar2, assume_unique=False):
"""
Find the set difference of two arrays.
"""
pass
[docs]
@numpy_method
def setxor1d(self, ar1, ar2, assume_unique=False):
"""
Find the set exclusive-or of two arrays.
"""
pass
[docs]
@numpy_method
def union1d(self, ar1, ar2):
"""
Find the union of two arrays.
"""
pass
###################################
# SORTING, SEARCHING AND COUNTING #
# See https://docs.scipy.org/doc/numpy/reference/routines.sort.html
# Sorting
[docs]
@numpy_method
def sort(self, a, axis=-1, kind="quicksort", order=None):
"""
Return a sorted copy of an array.
"""
pass
[docs]
@numpy_method
def lexsort(self, keys, axis=-1):
"""
Perform an indirect sort using a sequence of keys.
"""
pass
[docs]
@numpy_method
def argsort(self, a, axis=-1, kind="quicksort", order=None):
"""
Returns the indices that would sort an array.
"""
pass
[docs]
@numpy_method
def msort(self, a):
"""
Return a copy of an array sorted along the first axis.
"""
pass
[docs]
@numpy_method
def sort_complex(self, a):
"""
Sort a complex array using the real part first, then the imaginary part.
"""
pass
[docs]
@numpy_method
def partition(self, a, kth, axis=-1, kind="quicksort", order=None):
"""
Return a partitioned copy of an array.
"""
pass
[docs]
@numpy_method
def argpartition(self, a, kth, axis=-1, kind="quicksort", order=None):
"""
Perform an indirect partition along the given axis using the algorithm specified by the kind keyword.
"""
pass
# Searching
[docs]
@numpy_method
def argmax(self, a, axis, out=None):
"""
Returns the indices of the maximum values along an axis.
"""
pass
[docs]
@numpy_method
def nanargmax(self, a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring NaNs.
"""
pass
[docs]
@numpy_method
def argmin(self, a, axis, out=None):
"""
Returns the indices of the minimum values along an axis.
"""
pass
[docs]
@numpy_method
def nanargmin(self, a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring NaNs.
"""
pass
[docs]
@numpy_method
def argwhere(self, a):
"""
Find the indices of array elements that are non-zero, grouped by element.
"""
pass
[docs]
@numpy_method
def nonzero(self, a):
"""
Return the indices of the elements that are non-zero.
"""
pass
[docs]
@numpy_method
def flatnonzero(self, a):
"""
Return indices that are non-zero in the flattened version of a.
"""
pass
[docs]
@numpy_method
def where(self, condition, x, y):
"""
Return elements, either from x or y, depending on condition.
"""
pass
[docs]
@numpy_method
def searchsorted(self, a, v, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
"""
pass
# Counting
[docs]
@numpy_method
def count_nonzero(self, a, axis=None):
"""
Counts the number of non-zero values in the array a.
"""
pass
##############
# STATISTICS #
# See https://docs.scipy.org/doc/numpy/reference/routines.sort.html
# Order statistics
[docs]
@numpy_method
def amin(self, a, axis=None, out=None):
"""
Return the minimum of an array or minimum along an axis.
"""
pass
[docs]
@numpy_method
def amax(self, a, axis=None, out=None):
"""
Return the maximum of an array or maximum along an axis.
"""
pass
[docs]
@numpy_method
def nanmin(self, a, axis=None, out=None):
"""
Return minimum of an array or minimum along an axis, ignoring any NaNs.
"""
pass
[docs]
@numpy_method
def nanmax(self, a, axis=None, out=None):
"""
Return the maximum of an array or maximum along an axis, ignoring any NaNs.
"""
pass
[docs]
@numpy_method
def ptp(self, a, axis=None, out=None):
"""
Range of values (maximum - minimum) along an axis.
"""
pass
[docs]
@numpy_method
def percentile(
self, a, q, axis=None, out=None, overwrite_input=False, interpolation="linear"
):
"""
Compute the qth percentile of the data along the specified axis.
"""
pass
[docs]
@numpy_method
def nanpercentile(
self, a, q, axis=None, out=None, overwrite_input=False, interpolation="linear"
):
"""
Compute the qth percentile of the data along the specified axis,
while ignoring nan values.
"""
pass
# Averages and variances
[docs]
@numpy_method
def average(self, a, axis=None, weights=None, returned=False):
"""
Compute the weighted average along the specified axis.
"""
pass
[docs]
@numpy_method
def mean(self, a, axis=None, dtype=None, out=None):
"""
Compute the arithmetic mean along the specified axis.
"""
pass
[docs]
@numpy_method
def std(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the standard deviation along the specified axis.
"""
pass
[docs]
@numpy_method
def var(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the variance along the specified axis.
"""
pass
[docs]
@numpy_method
def nanmean(self, a, axis=None, dtype=None, out=None):
"""
Compute the arithmetic mean along the specified axis, ignoring NaNs.
"""
pass
[docs]
@numpy_method
def nanstd(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the standard deviation along the specified axis, while ignoring NaNs.
"""
pass
[docs]
@numpy_method
def nanvar(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the variance along the specified axis, while ignoring NaNs.
"""
pass
# Correlating
[docs]
@numpy_method
def corrcoef(self, x, y, rowvar=1):
"""
Return Pearson product-moment correlation coefficients.
"""
pass
[docs]
@numpy_method
def correlate(self, a, v, mode="valid"):
"""
Cross-correlation of two 1-dimensional sequences.
"""
pass
[docs]
@numpy_method
def cov(
self,
m,
y=None,
rowvar=True,
bias=False,
ddof=None,
fweights=None,
aweights=None,
):
"""
Estimate a covariance matrix, given data and weights.
"""
pass
# Histograms
[docs]
@numpy_method
def histogram(
self, a, bins=10, range=None, normed=False, weights=None, density=None
):
"""
Compute the histogram of a set of data.
"""
pass
[docs]
@numpy_method
def histogram2d(self, x, y, bins, range=None, normed=False, weights=None):
"""
Compute the bi-dimensional histogram of two data samples.
"""
pass
[docs]
@numpy_method
def histogramdd(self, sample, bins, range=None, normed=False, weights=None):
"""
Compute the multidimensional histogram of some data.
"""
pass
[docs]
@numpy_method
def bincount(self, x, weights=None, minlength=None):
"""
Count number of occurrences of each value in array of non-negative ints.
"""
pass
[docs]
@numpy_method
def digitize(self, x, bins, right=False):
"""
Return the indices of the bins to which each value in input array belongs.
"""
pass
ArrayBackend._register_backend(np.ndarray, HostArrayBackend)
ArrayBackend._register_backend(HostBuffer, HostArrayBackend)